#coding:utf8
from info import constants, db
from info.models import News, Category, User
from info.utils.common import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import profile_blu
from flask import render_template, redirect, g, request, jsonify, current_app

#获取作者信息,新闻列表
# 请求路径: /user/other_news_list
# 请求方式: GET
# 请求参数:p,user_id
# 返回值: errno,errmsg
@profile_blu.route('/other_news_list')
def other_news_list():

    #1.获取参数,页数
    page = request.args.get("p",1)
    author_id = request.args.get("user_id")

    if not author_id:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    #3.分页查询,获取作者对象
    try:
        #作者对象
        author = User.query.get(author_id)

        #分页查询
        paginate = author.news_list.paginate(page,constants.OTHER_NEWS_PAGE_MAX_COUNT,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询异常")

    #4.获取分页对象数据,总页数,当前页,对象列表
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    #5.对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    #6.拼接data数据,返回页面渲染
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }

    return jsonify(errno=RET.OK,errmsg="获取成功",data=data)



#获取作者信息
# 请求路径: /user/other
# 请求方式: GET
# 请求参数:id
# 返回值: 渲染other.html页面,字典data数据
@profile_blu.route('/other')
@user_login_data
def other():

    #1.获取参数,作者编号
    author_id = request.args.get("id")

    if not author_id:
        return jsonify(errno=RET.PARAMERR,errmsg="作者编号为空")

    #2.通过作者编号取出作者对象
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库库查询异常")

    if not author:
        return jsonify(errno=RET.NODATA,errmsg="该作者不存在")

    #3.判断是否关注了当前作者
    is_followed = False
    if g.user:
        if g.user in author.followers:
            is_followed = True

    #4.封装数据,渲染页面
    data = {
        "user_info":g.user.to_dict() if g.user else None,
        "is_followed":is_followed,
        "author":author.to_dict()
    }

    return render_template('news/other.html',data=data)




#获关注列表
# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:p
# 返回值: 渲染user_follow.html页面,字典data数据
@profile_blu.route('/user_follow')
@user_login_data
def user_follow():

    #1.获取参数,页数
    page = request.args.get("p",1)

    #2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    #3.分页查询
    try:
        paginate = g.user.followed.paginate(page,3,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询异常")

    #4.获取分页对象数据,总页数,当前页,对象列表
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    #5.对象列表转成字典列表
    author_list = []
    for author in items:
        author_list.append(author.to_dict())

    #6.拼接data数据,返回页面渲染
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "author_list":author_list
    }

    return render_template('news/user_follow.html',data=data)



#新闻列表展示
@profile_blu.route('/news_list')
@user_login_data
def news_list():

    #1.获取页数,p
    page =  request.args.get("p",1)

    #2.参数转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    #3.分页查询,新闻列表
    try:
        paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,3,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询异常")

    #4.获取出分页对象中的总页数,当前页,对象列表
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    #5.对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    #6.渲染到页面中
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }
    return render_template('news/user_news_list.html',data=data)



#新闻发布
# 请求路径: /user/news_release
# 请求方式:GET,POST
# 请求参数:GET无, POST ,title, category_id,digest,index_image,content
# 返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():

    # 1.如果第一次请求,GET,直接渲染页面
    if request.method == 'GET':

        try:
            categoies = Category.query.all()
            #弹出最新信息
            categoies.pop(0)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="分类查询异常")

        #转成字典列表
        category_list = []
        for category in categoies:
            category_list.append(category.to_dict())

        return render_template('news/user_news_release.html',data={"categories":category_list})

    #2.获取参数,校验参数(为空校验)
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")

    if not all([title,category_id,digest,content,index_image]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    #图片上传
    try:
        #读取图片
        image_data = index_image.read()

        #上传图片
        image_name = image_storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云上传异常")

    #判断图片是否上传成功
    if not image_name:
        return jsonify(errno=RET.NODATA,errmsg="图片上传失败")

    #3.创建新闻对象
    news = News()

    #4.设置新闻对象属性
    news.title = title
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    #刚发布,属于审核状态
    news.status = 1

    #5.添加到数据库中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)

    #6.返回响应
    return jsonify(errno=RET.OK ,errmsg="发布成功")




#用户收藏新闻
# 请求路径: /user/collection
# 请求方式:GET
# 请求参数:GET, p(页数)
# 返回值:GET请求: user_collection.html页面,data字典数据
@profile_blu.route('/collection')
@user_login_data
def get_collection():

    #1.获取参数
    page =  request.args.get("p",1)

    #2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    #3.分页查询用户收藏的新闻
    try:
        #分页查询第page页,每页有10条,不进行错误输出
        paginate = g.user.collection_news.paginate(page,1,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询异常")

    #4.获取到分页对象中的参数,总页数,当前页,内容
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    #5.将新闻对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    #6.返回数据到页面中渲染
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }
    return render_template('news/user_collection.html',data=data)


#修改密码
# 请求路径: /user/pass_info
# 请求方式:GET,POST
# 请求参数:GET无, POST有参数,old_password, new_password
# 返回值:GET请求: user_pass_info.html页面,data字典数据, POST请求: errno, errmsg
@profile_blu.route('/pass_info',methods=["GET","POST"])
@user_login_data
def pass_info():

    # 1.如果第一次请求,GET,直接渲染页面
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 2.获取参数,为空校验
    dict_data = request.json
    old_password = dict_data.get("old_password")
    new_password = dict_data.get("new_password")

    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    # 3.正确性校验,老密码
    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR,errmsg="原密码错误")

    #4.设置新密码
    g.user.password = new_password

    #5.返回响应
    return jsonify(errno=RET.OK,errmsg="修改密码成功")




#上传用户头像
# 请求路径: /user/pic_info
# 请求方式:GET,POST
# 请求参数:无, POST有参数,avatar
# 返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():

    #1.如果第一次请求,GET,直接渲染页面
    if request.method == 'GET':
        return render_template('news/user_pic_info.html')

    #2.获取参数
    file_image =  request.files.get("avatar")

    #3.校验参数
    if not file_image:
        return jsonify(errno=RET.NODATA,errmsg="参数不能为空")

    #4.上传头像
    try:
        #读取图片
        image_data = file_image.read()
        #上传图像
        image_name = image_storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云上传异常")

    #5.设置到用户,avatar_url
    g.user.avatar_url = image_name

    #6.返回响应
    data = {"avatar_url":constants.QINIU_DOMIN_PREFIX  + image_name}
    return jsonify(errno=RET.OK,errmsg="图片上传成功",data=data)



#基本信息
# 请求路径: /user/base_info
# 请求方式:GET,POST
# 请求参数:POST请求有参数,nick_name,signature,gender
# 返回值:errno,errmsg
@profile_blu.route('/base_info',methods=["GET","POST"])
@user_login_data
def base_info():

    #1.第一次进来,是GET请求,直接渲染页面
    if request.method == "GET":
        data= {"user_info":g.user.to_dict()}

        return render_template('news/user_base_info.html',data=data)

    #2.获取数据
    dict_data = request.json
    nick_name = dict_data.get("nick_name")
    signature = dict_data.get("signature")
    gender = dict_data.get("gender")

    #3.校验参数
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    if not gender in ["MAN","WOMAN"]:
        return jsonify(errno=RET.DATAERR,errmsg="性别类型错误")

    #4.设置到用户对象属性中
    g.user.nick_name = nick_name
    g.user.signature = signature
    g.user.gender = gender

    #5.返回响应
    return jsonify(errno=RET.OK,errmsg="个人信息设置成功")


#个人中心页面
@profile_blu.route('/user_info')
@user_login_data
def get_user_info():

    #判断用户是否登陆
    if not g.user:
        return redirect('/')

    #获取用户数据
    data = {
        "user_info":g.user.to_dict()
    }

    return render_template('news/user.html',data=data)